<template>
  <el-card>
    <div style="margin-bottom: 16px;">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column 
        v-for="col in columns" 
        :key="col.prop" 
        :prop="col.prop" 
        :label="col.label"
        :formatter="(row) => props.formatter?.[col.prop] ? props.formatter[col.prop](row[col.prop]) : row[col.prop]"
      />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑' : '新增'">
      <el-form :model="form">
        <el-form-item v-for="col in columns" :key="col.prop" :label="col.label">
          <el-input v-model="form[col.prop]" :disabled="col.prop==='id' && isEdit" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  columns: Array,
  api: Object,
  formatter: Object
})

const tableData = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive({})

function fetchData() {
  props.api.list().then(res => {
    tableData.value = res.data || res // 兼容不同返回结构
  })
}

function handleAdd() {
  Object.keys(props.columns).forEach(i => {
    form[props.columns[i].prop] = ''
  })
  isEdit.value = false
  dialogVisible.value = true
}

function handleEdit(row) {
  Object.assign(form, row)
  isEdit.value = true
  dialogVisible.value = true
}

function handleDelete(row) {
  props.api.del(row.id).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  })
}

function handleSubmit() {
  const action = isEdit.value ? props.api.update : props.api.add
  action({ ...form }).then(() => {
    ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
    dialogVisible.value = false
    fetchData()
  })
}

watch(() => props.api, fetchData, { immediate: true })
</script>